<?php

namespace app\admin\controller;

use app\common\model\ItemWare;
use Curl\Curl;
use think\Request;
use app\common\controller\Base;
use app\common\model\ItemWare as ItemWareModel;
use app\common\model\User as UserModel;
use \Redis;


class Taobao extends Base
{
    /**
     * 所以过滤都是在python当中过滤了 php就不参与过滤了 默认的上传的配置参数 保证每个参数都有值
     * 用户采集淘宝的基本配置参数 默认这写过滤的功能都做
     *   'price' => [0=>['percent'=>100,'increment'=>''],100=>['percent'=>100,'increment'=>1],...]   价格设置
     *   'keep_origin_url'=>'1'   是否保留原来的链接 隐藏链接设置
     *   'modify_brand' => '1'    属性中的品牌是否改成其他
     *   'filter_sys_brand'=>'1'  标题是否过滤系统品牌库中的品牌     只有过滤的才需要传递到python
     *   'filter_sys_title'=>'1'  标题是否过滤系统禁用关键词
     *  'filter_sellerNick' =>'1', 过滤旺旺
     *  'filter_shopName' => '1',  过滤店铺名字
     * @var string
     */
    protected $userTaobaoConfig = [
        'price' => [0=>['percent'=>100,'increment'=>'0']],
        'keep_origin_url'=>'1',
        'filter_sys_brand'=>'0',
        'filter_sys_title'=>'0',
        'modify_brand' => '1',
        'filter_sellerNick' =>'0',
        'filter_shopName' => '0',
    ];

    public function __construct(Request $request){
        parent::__construct($request);
    }
    public function index(){

        return view();
    }

    public function add(){
        return view();
    }

    public function edit(){
        return view();
    }


    public function create(){

    }


    public function update(){

    }


    public function delete(){

    }


    /**
     * 批量采集
     */
    public function getItems(){

        return view();
    }


    /**
     * 手动添加一个路径到仓库
     */
    public function addItemToWare(){

        return view();
    }

    public function itemEdit(){
        return '';
    }

    public function itemDelete(Request $request){
        if(!$request -> isDelete()){
            $this->error("非法渠道访问");
        }
        $id = $request->param('id',0,'intval');
        ItemWareModel::destroy($id);
        $this->success("操作成功");
    }

    /**
     * 采集的库
     */
    public function itemWare(){

        $items = ItemWare::where('user_id',$this->user->id)->order('id desc')->paginate(20);

        return view('',['items'=>$items]);
    }

    public function itemsCreate(){

    }

    public function itemCreate(Request $request){
        if(!$request->isPost()){
            $this->error("非法渠道访问");
        }
        $data = $request->only('url');
        $data['user_id'] = $this->user->id;
        $itemWare = new ItemWare();
        $itemWare->save($data);
        $this->success("操作成功");
    }

    public function addToQueue(Request $request){
        //$this->user->taobaosession = '6202612f8c847fc88cc1ZZf88859cfa9560332f27de6a55314210378';
        if(!$this->user->taobaosession && $this->user->expire_time < time()){
            $this->error("请先登录淘宝");
        }
        $id = $request->param('id',0,'intval');
        $item = ItemWareModel::find($id);
        if($item->status >= 1){
            $this->success("加入到上传队列成功");
        }
        $redis = new Redis();
        $redis->connect('localhost');

        $taobaoConfig = Config('taobao');
        $taskQueue = $taobaoConfig['taskQueue'];
        $redis->lpush($taskQueue,json_encode(
            ['itemwareid'=>$item['id'],
            'url'=>$item->url,
            'userid'=>$this->user->id,
            'taobaosession'=>$this->user->taobaosession,
            'filter_sys_brand'=>$this->userTaobaoConfig['filter_sys_brand'],
            'filter_sys_title'=>$this->userTaobaoConfig['filter_sys_title'],
            'filter_sellerNick' =>$this->userTaobaoConfig['filter_sellerNick'],
            'filter_shopName' => $this->userTaobaoConfig['filter_shopName'],
            ]
        ));
        $item->status = 1;
        $item->save();
        $this->success("加入到队列成功");
    }


    /**
     * 批量加入上传
     * 利用采集过来的数据
     */
    public function addToQueueFromSpider(Request $request){
        if(!$this->user->taobaosession && $this->user->expire_time < time()){
            $this->error("请先登录淘宝");
        }

        $data = $request->param();
        $data = $data['data'];

        //排除重复的
        $urls = array_column($data,'url');
        $exists = ItemWareModel::whereIn('url',$urls)->where('user_id',$this->user['id'])->column('url');
        if($exists){
            foreach($data as $key => $val ){
                if(in_array($val['url'],$exists)){
                    unset($data[$key]);
                }else{
                    //顺便构造一下数据
                    $data[$key]['user_id'] = $this->user['id'];
                    $data[$key]['status'] = '1';
                }
            }
        }else{
            foreach($data as $key => $val ){
                //顺便构造一下数据
                $data[$key]['user_id'] = $this->user['id'];
                $data[$key]['status'] = '1';
            }
        }

        //剩下的没有重复的数据
        //批量加入到数据
        $itemWareModel = new ItemWareModel();
        $data = $itemWareModel -> saveAll($data);

        //批量加入到队列
        $redis = new Redis();
        $redis->connect('localhost');

        $taobaoConfig = Config('taobao');
        $taskQueue = $taobaoConfig['taskQueue'];
        foreach($data as $key => $val ){
            $redis->lpush($taskQueue,json_encode(
                [
                    'itemwareid'=>$val['id'],
                    'url'=>$val->url,
                    'userid'=>$this->user->id,
                    'taobaosession'=>$this->user->taobaosession,
                    'filter_sys_brand'=>$this->userTaobaoConfig['filter_sys_brand'],
                    'filter_sys_title'=>$this->userTaobaoConfig['filter_sys_title'],
                    'filter_sellerNick' =>$this->userTaobaoConfig['filter_sellerNick'],
                    'filter_shopName' => $this->userTaobaoConfig['filter_shopName'],
                ]));
        }

        $this->success("加入到队列成功");
    }

    /**
     * 批量采集
     * @param Request $request
     * @return \think\response\View
     */
    public function spiderLots(Request $request){
        if(!$this->user->taobaosession && $this->user->expire_time < time()){
            $this->error("请先登录淘宝",'/admin/login/index');
        }
        if($request->isPost()){
            $baseUrl = 'http://pub.alimama.com/items/search.json?';
            $params = $request->param();

            $search = [];
            foreach($params as $key => $val ){
                //如果所有的都对接的话 淘宝会认为是采集 会被封 以后可能需要买代理
                if($val){
                    array_push($search,$key.'='.$val);
                }
            }


            $condition = implode('&',$search);
            $searchUrl = $baseUrl.$condition;
            //echo $searchUrl;exit;
            $curl = new Curl();
            $curl->setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.7.0.16013");
            $curl->get($searchUrl);
            $response = json_decode($curl->response,true);

            $pageList = [];
            if($response && isset($response['data']['pageList'])){
                $pageList = $response['data']['pageList'];
            }

            return view('',['pageList'=>$pageList,'condition'=>$params]);
        }
        return view('',['pageList'=>[],'condition'=>[]]);
    }



    public function doSpiderLots(Request $request){
        $baseUrl = 'http://pub.alimama.com/items/search.json?';
        $curl = new Curl();
        $curl->get($baseUrl);
        $response = json_decode($curl->response,true);
        var_dump($response['data']);
    }


    public function myConfig(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(isset($param['price'])){
                $price = [];
                foreach( $param['price']['origin'] as $key => $val ){
                    $price[$val] = ['percent'=>$param['price']['percent'][$key],'increment'=>$param['price']['increment'][$key]];
                }

                $param['price'] = $price;
            }
            $taobaoConfig = $param;
            $param = serialize($param);
            UserModel::update(['taobao_config'=>$param],['id'=>$this->user->id]);
            return view('',['taobaoConfig'=>$taobaoConfig]);
        }

        $taobaoConfig = UserModel::where('id',$this->user->id)->value('taobao_config');
        $taobaoConfig = unserialize($taobaoConfig);
        return view('',['taobaoConfig'=>$taobaoConfig]);
    }

    /**
     *
     */
    public function testWork(){
        //$redis = new Redis();
        //$redis->connect("localhost");
        //$toDo = $redis->rpop($this->phpitemqueue);
        //$toDo = json_decode($toDo,true);
        $toDo = ['itemwareid'=>'1','url' => 'http://www.baidu.com', 'userid' => 3,  'taobaosession' => '620063094e83559cb9e9f8e96429742b69139egi7b0595c314210378'];
        //分析出itemid
        $url = $toDo['url'];
        $res = preg_match('/id=(\d+)/',$url,$match);
        //通过itemid 去寻找

        if(!$res){
            //没有匹配到id就记录采集失败 url非法
            ItemWareModel::update(['status'=>3,'process_msg'=>'商品网址错误'],['id'=>$toDo['itemwareid']]);
        }else{
            $id = $match[1];
        }
    }






}

